package com.duowan.cms.common.webapp.init;

import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;

/**
 *  初始化处理器
 * @author coolcooldee
 *
 */
public abstract class InitializingProcessor {

    protected static final Log LOG = LogFactory.getLog(InitializingProcessor.class);

    /**
     * 初始化执行实现了InitializingBean接口Bean中的init()方法
     * @param ctx
     */
    public static void doInitInitializingBeans(ApplicationContext ctx) {
        @SuppressWarnings("unchecked")
        Map<String, InitializingBean> initBeans = ctx.getBeansOfType(InitializingBean.class);
        if (initBeans == null || initBeans.isEmpty())
            return;

        for (Entry<String, InitializingBean> entry : initBeans.entrySet()) {
            if (LOG.isInfoEnabled())
                LOG.info("InitializingBean[" + entry.getKey() + "]初始化开始");
            try {
                entry.getValue().init();
            } catch (Throwable e) {
                LOG.error("InitializingBean[" + entry.getKey() + "]初始化失败", e);
            }
            if (LOG.isInfoEnabled())
                LOG.info("InitializingBean[" + entry.getKey() + "]初始化结束");
        }
    }

    /**
     * 初始化执行实现了ServletContextInitializingBean接口Bean中的initialized(ServletContext servletContext)方法
     * @param ctx
     */
    public static void doInitInitializingBeans(ApplicationContext ctx, ServletContext servletContext) {
        @SuppressWarnings("unchecked")
        Map<String, ServletContextInitializingBean> initBeans = ctx.getBeansOfType(ServletContextInitializingBean.class);
        if (initBeans == null || initBeans.isEmpty())
            return;

        for (Entry<String, ServletContextInitializingBean> entry : initBeans.entrySet()) {
            if (LOG.isInfoEnabled())
                LOG.info("ServletContextInitializingBean[" + entry.getKey() + "]初始化开始");
            try {
                entry.getValue().initialized(servletContext);
            } catch (Throwable e) {
                LOG.error("ServletContextInitializingBean[" + entry.getKey() + "]初始化失败", e);
            }
            if (LOG.isInfoEnabled())
                LOG.info("ServletContextInitializingBean[" + entry.getKey() + "]初始化结束");
        }
    }

}
